import pikepdf
import os
import sys

# 启动： python unpdf_v0.2_win_dir.py "D:\pdf" "D:\unpdf"
# 参数为： 输入文件夹 输出文件夹

def check_file_dir(file):
    dir = file
    if not os.path.isdir(file):
        dir = os.path.dirname(file)
    if not os.path.exists(dir):
        os.makedirs(dir)

def unpdf_dir(inDirectory, outDirectory):
    # 遍历目录下的所有文件
    for root, dirs, files in os.walk(inDirectory):
        for file in files:
            # 检查文件是否为 PDF 文件
            if file.endswith('.pdf'):
                # 打开 PDF 文件
                filename = os.path.join(root, file)
                pdf = pikepdf.open(os.path.join(inDirectory, filename))
                # 保存为未加密的 PDF 文件
                outFileName = filename.replace(inDirectory, outDirectory)
                check_file_dir(outFileName)
                pdf.save(outFileName)
                print(f'解密完成:{outFileName}')

if __name__ == '__main__':
    print(sys.argv)
    inDirectory = sys.argv[1]
    outDirectory = sys.argv[2]
    unpdf_dir(inDirectory,outDirectory)
    print('解密完成。 Unloked done.')
    # os.system("pause") # 请按任意键继续. . .

